package com.steve.summary.seata.service.impl;

import com.steve.summary.seata.dto.OrderDTO;
import com.steve.summary.seata.entity.Order;
import com.steve.summary.seata.feign.AccountFeignClient;
import com.steve.summary.seata.feign.StorageFeignClient;
import com.steve.summary.seata.mapper.OrderMapper;
import com.steve.summary.seata.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: STEVE
 * @Description: 订单服务实现
 * @since: 2025-07-08
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private StorageFeignClient storageFeignClient;

    @Autowired
    private AccountFeignClient accountFeignClient;

    /**
     * 创建订单 - 分布式事务入口
     *
     * @param orderDTO 订单传输对象
     */
    @Override
    @GlobalTransactional(name = "order-create", timeoutMills = 300000, rollbackFor = Exception.class)
    @Transactional(rollbackFor = Exception.class)
    public void createOrder(OrderDTO orderDTO) {
        log.info("===== 开始创建订单全局事务 =====");

        // 1. 扣减库存（远程服务调用）
        log.info("--> 调用库存服务扣减库存");
        storageFeignClient.decrease(orderDTO.getProductId(), orderDTO.getCount());

        // 2. 创建订单（本地事务）
        log.info("--> 创建订单数据");
        Order order = new Order();
        BeanUtils.copyProperties(orderDTO, order);
        order.setStatus(0); // 0-创建中
        orderMapper.insert(order);

        // 3. 扣减账户余额（远程服务调用）
        log.info("--> 调用账户服务扣减余额");
        accountFeignClient.decrease(orderDTO.getUserId(), orderDTO.getMoney());

        // 4. 更新订单状态（本地事务）
        log.info("--> 更新订单状态为已完成");
        order.setStatus(1); // 1-已完成
        orderMapper.updateById(order);

        log.info("===== 订单创建成功 =====");
    }

    /**
     * 查询订单详情
     *
     * @param orderId 订单ID
     * @return
     */
    @Override
    public Order getOrderDetail(Long orderId) {
        return orderMapper.selectById(orderId);
    }

    /**
     * 更新订单状态
     *
     * @param orderId 订单ID
     * @param status  新状态
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderStatus(Long orderId, Integer status) {
        Order order = new Order();
        order.setId(orderId);
        order.setStatus(status);
        orderMapper.updateById(order);
    }

}
